package com.lwq.advice;

import com.lwq.exception.ApiException;
import com.lwq.exception.AuthenticationException;
import com.lwq.util.ExceptionUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2021/6/10
 */
@ControllerAdvice
@ResponseBody
public class ExceptionAdivce {

    private Logger log = LoggerFactory.getLogger(ExceptionAdivce.class);

    /**
     * 全局捕获401异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<?> authenticationException(Exception e){
        if(e instanceof AuthenticationException){
            return new ResponseEntity<>(StringUtils.isEmpty(e.getMessage()) ? "验证失败" : e.getMessage(),
                                    HttpStatus.UNAUTHORIZED);
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }

    /**
     * 全局捕获500异常
     * @param e
     * @return
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<?> apiException(Exception e){
        if(e instanceof ApiException){
            return new ResponseEntity<>(StringUtils.isEmpty(e.getMessage()) ? "系统繁忙" : e.getMessage(),
                    HttpStatus.INTERNAL_SERVER_ERROR);
        }
        this.log.error("服务端出现500异常---------------->");
        ExceptionUtil.printStackTrace(e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }


    /**
     * 全局捕获hibernate字段验证异常
     * @param exception
     * @return
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> methodArgumentNotValidException(MethodArgumentNotValidException exception){
        BindingResult result = exception.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            if (errors != null) {
                errors.forEach(p -> {
                    FieldError fieldError = (FieldError) p;
                    stringBuilder.append(fieldError.getDefaultMessage()+",");
                });
            }
        }
        return new ResponseEntity<>(stringBuilder.toString().substring(0,stringBuilder.toString().length()-1),
                HttpStatus.BAD_REQUEST);
    }
}
